﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Configuration;
using System.Threading;
using System.IO;
using TcpLabCommon;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using TCPIPControl.StructHelper;
using TCPIPControl;

namespace Common
{
    public enum TcpIpState
    {
        //连接并握手成功
        Connection = 0,
        //Ping不通
        Disconnection = 1,
        //Ping但无法握手,故障
        Fault = 2,
        //tcpip都无法连接
        Fail =3
    }

    public enum TcpIpMode
    {
        SlowMode = 0,
        FastMode = 1
    }

    public class TcpIpControl
    {
        public delegate void UpdateViewHandler(NetPacket packet);

        public delegate void UpdateViewWithMsgHandler(string msg);

        public List<ACQParametersConfig> RecieveListACQ = new List<ACQParametersConfig>();

        public List<TestPointConfig> RecieveListTPC = new List<TestPointConfig>();

        public List<TCPIPControl.StructHelper.SpeedConfig> RecieveListSC = new List<TCPIPControl.StructHelper.SpeedConfig>();

        public List<string> RecieveListString = new List<string>();

        public List<DataPacket> RecieveListSlowModeDataPacket = new List<DataPacket>();

        public List<DataPacket> RecieveListFastModeDataPacket = new List<DataPacket>();

        public List<TCPIPControl.StructHelper.ChannelConfig> RecieveListChannelConfig = new List<TCPIPControl.StructHelper.ChannelConfig>();

        public DataPacket CurrentDataPacket;

        public CurrentDataPacketAndFFTData CurrentCustomData;

        Cls_ping MyPing = new Cls_ping();

        public TcpIpState MyTcpIpState = TcpIpState.Fault;

        public TcpIpMode MyTcpIpMode = TcpIpMode.SlowMode;

        public long DisConnTimes = 0;

        public long HeatBeat = 0;
        public long OldHeatBeat = 0;
        public string ACQSet = "";
        public string ChannelSet = "";
        public int sendErrcount = 0;//发送错误次数
        /// <summary>
        /// Tcp服务对象[提供发包和收包功能]，接收消息和文件使用
        /// </summary>
        Cls_NetPacketService tcpPacketServiceSvr = null;

        /// <summary>
        /// Tcp服务对象[提供发包和收包功能],发送消息和文件使用
        /// </summary>
        Cls_NetPacketService tcpPacketServiceClient = null;

        /// <summary>
        /// 客户端Socket[发送消息和文件]
        /// </summary>
        public Socket clientSocket = null;

        /// <summary>
        /// 本地服务器名
        /// </summary>
        public string ServerName
        {
            get;
            set;
        }

        /// <summary>
        /// 本地监听端口
        /// </summary>
        public Int32 ServerPort
        {
            get;
            set;
        }

        /// <summary>
        /// 对方服务器名
        /// </summary>
        public String RemoteServerName
        {
            get;
            set;
        }

        /// <summary>
        /// 对方服务器监听端口
        /// </summary>
        public Int32 RemoteServerPort
        {
            get;
            set;
        }

        TcpAsynHandler1 _delegateReceivedPacket = null;

        TcpAsynHandler2 _delegateSendPacket = null;
        //Socket serverSocket = null;
        EndPoint endPoint = null;

        public Cls_ACQUnit Master = null;



        public TcpIpControl(string IP,int port)
        {
      
            HeatBeat = 0;
            OldHeatBeat = 0;
            RecieveListACQ.Clear();
            RecieveListString.Clear();
            RecieveListSlowModeDataPacket.Clear();
            RecieveListChannelConfig.Clear();
            RecieveListFastModeDataPacket.Clear();

            this.RemoteServerName = IP;
            this.RemoteServerPort = port;
            //this.ServerName = Master.HostIPAddress;
            //this.ServerPort = Master.HostPort;

            //初始化两个事件的委托
            _delegateReceivedPacket = new TcpAsynHandler1(Classification);
            _delegateSendPacket = new TcpAsynHandler2(SendRecord);
        }

        public bool Init()
        {
            try
            {
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //endPoint = new IPEndPoint(IPAddress.Parse(ServerName), ServerPort);//创建一个终结点
                //serverSocket.Bind(endPoint);//绑定终结点
   
                clientSocket.Connect(IPAddress.Parse(RemoteServerName), RemoteServerPort);
                
                  if (clientSocket.Connected)
                {
             
                    NetworkStream netStream = new NetworkStream(clientSocket);
                    tcpPacketServiceClient = new Cls_NetPacketTcpAsynService(netStream);
                    tcpPacketServiceSvr = tcpPacketServiceClient;
                    (tcpPacketServiceClient as Cls_NetPacketTcpAsynService).workerThreadExceptionHandlerDelegate = new TcpLabCommon.WorkerThreadExceptionHandlerDelegate(WorkerThreadExceptionHandler);

                    (tcpPacketServiceClient as Cls_NetPacketTcpAsynService).OnReceivedPacket += _delegateReceivedPacket;

                    tcpPacketServiceClient.ReceivePacket();                                                                //serverSocket.EndAccept();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                tcpPacketServiceClient = null;
                tcpPacketServiceSvr = null;
                Console.WriteLine(ex.Message);
                return false;
            }
        }

        private void AsyncCallbackAccept(IAsyncResult result)
        {
            try
            {
                Socket serverSocket = (Socket)result.AsyncState;
                Socket ctSocket = serverSocket.EndAccept(result);
                NetworkStream netStream = new NetworkStream(ctSocket);
                tcpPacketServiceSvr = new Cls_NetPacketTcpAsynService(netStream); 
                (tcpPacketServiceSvr as Cls_NetPacketTcpAsynService).workerThreadExceptionHandlerDelegate = new TcpLabCommon.WorkerThreadExceptionHandlerDelegate(WorkerThreadExceptionHandler);

                (tcpPacketServiceSvr as Cls_NetPacketTcpAsynService).OnReceivedPacket += _delegateReceivedPacket;

                tcpPacketServiceSvr.ReceivePacket();
            }
            catch (Exception e)
            {
                WorkerThreadExceptionHandler(e);
            }
        }

        void WorkerThreadExceptionHandler(Exception e)
        {
            /**/
            ///添加其他的处理代码
            ///通知全局异常处理程序
            MainUIThreadExceptionHandler(this, new System.Threading.ThreadExceptionEventArgs(e));
        }

        void MainUIThreadExceptionHandler(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            try
            {


                string a = e.ToString();
                //客户端断线的处理
     
                clientSocket.Close(100);
                tcpPacketServiceClient = null;
                tcpPacketServiceSvr = null;
                clientSocket = null;

                if (Mdl_Class.frmMainState == 1)
                {
                    Init();
                }
            }
            catch (Exception ex)
            {

                Mdl_Class.WriteLog.sysErrLog("退出scoket异常：", ex.ToString());
            }
        }

        public void Dispose()
        {
            //向下位机发送断开命令;
            try
            {


            Thread.Sleep(100);
                tcpPacketServiceClient = null;
                tcpPacketServiceSvr = null;
                if (clientSocket!=null) {
                    clientSocket.Close();
                    clientSocket.Disconnect(true);
                }

            }
            catch (Exception ex)
            {


                Mdl_Class.WriteLog.sysErrLog("退出scoket异常：", ex.ToString());
            }
        }

        public void Reconnect()
        {
            if ((this.tcpPacketServiceSvr as Cls_NetPacketTcpAsynService) != null)
            {
                (this.tcpPacketServiceSvr as Cls_NetPacketTcpAsynService).ClientNormalExitFlag = false;
            }
        }

        /// <summary>
        /// 发送时数据库记录
        /// </summary>
        /// <param name="packetHead"></param>
        void SendRecord(NetPacketHead packetHead)
        {
           // Console.WriteLine("服务器回了一包");
            //记录日志数据库
        }
        SaveData savedata = new SaveData();
        IAsyncResult result_String = null;
        public delegate void AddHandler_String(String datas);
        IAsyncResult result_ACQParametersConfig = null;
        public delegate void AddHandler_ACQParametersConfig(TCPIPControl.StructHelper.ACQParametersConfig datas);
        IAsyncResult result_AccData = null;
        public delegate void AddHandler_AccData();
        IAsyncResult result_DisplacementData = null;
        public delegate void AddHandler_DisplacementData();
        IAsyncResult result_SlowSignal = null;
        public delegate void AddHandler_SlowSignal();
        IAsyncResult result_SpeedData = null;
        public delegate void AddHandler_SpeedData();
        IAsyncResult result_SamplingConfig = null;
        public delegate void AddHandler_SamplingConfig();
        IAsyncResult result_MachineTime = null;
        public delegate void AddHandler_MachineTime(MachineTime datas);
        IAsyncResult result_Other= null;
        public delegate void AddHandler_Other(Object datas);
        /// <summary>
        /// 接收后放入缓存
        /// </summary>
        /// <param name="packet"></param>
        void Classification(NetPacket packet)
        {
            Mdl_Class.startTime = DateTime.Now;
            try
            {
                Mdl_Class.ConnectTime.Restart();
               
            switch (packet.PacketHead.PType)
            {
                case PacketType.STRING:
                    if (result_String == null || result_String.IsCompleted)
                    {
                        result_String = new AddHandler_String(savedata.SaveString).BeginInvoke(packet.Data.ToString(), null, null);
                    }
                    break;
                case PacketType.ACQParametersConfig:
                    TCPIPControl.StructHelper.ACQParametersConfig acq = (TCPIPControl.StructHelper.ACQParametersConfig)packet.Data;
                    Mdl_Class.acqParametersConfig = acq;
                    if (result_ACQParametersConfig == null || result_ACQParametersConfig.IsCompleted)
                    {
                        result_ACQParametersConfig = new AddHandler_ACQParametersConfig(savedata.SaveACQParametersConfig).BeginInvoke(acq, null, null);

                    }
                    break;
                case PacketType.AccelerationPacket:

                    if (Mdl_Class.IsQuitProgram)
                    {
                        return;
                    }
                    //AccData accdata = (AccData)packet.Data;
                  
                    Mdl_Class.accdatalist.Add(packet.Data);
                    if (result_AccData == null || result_AccData.IsCompleted)
                    {
                        result_AccData = new AddHandler_AccData(savedata.SaveAccData).BeginInvoke( null, null);

                    }
                    break;

                case PacketType.DisplacementPacket:
                    if (Mdl_Class.IsQuitProgram)
                    {
                        return;
                    }
                    DisplacementData displacementData = (DisplacementData)packet.Data;
                    Mdl_Class.displacementData = displacementData;
                    Mdl_Class.displacementDatalist.Add(displacementData);
                    if (result_DisplacementData == null || result_DisplacementData.IsCompleted)
                    {
                        result_DisplacementData = new AddHandler_DisplacementData(savedata.SaveDisplacementData).BeginInvoke( null, null);

                    }
                    break;
                case PacketType.SlowSignalPacket:
                    SlowSignal slowSignal = (SlowSignal)packet.Data;
                    Mdl_Class.slowSignal = slowSignal;
                    Mdl_Class.slowSignallist.Add(slowSignal);
                    if (result_SlowSignal == null || result_SlowSignal.IsCompleted)
                    {
                        result_SlowSignal = new AddHandler_SlowSignal(savedata.SaveSlowSignal).BeginInvoke(null, null);

                    }
                    break;
                case PacketType.SpeedPacket:
                    SpeedData speedData = (SpeedData)packet.Data;
                    Mdl_Class.speedData = speedData;
                    Mdl_Class.speedDatalist.Add(speedData);
                    if (result_SpeedData == null || result_SpeedData.IsCompleted)
                    {
                        result_SpeedData = new AddHandler_SpeedData(savedata.SaveSpeedData).BeginInvoke(null, null);

                    }
                    break;
                case PacketType.SamplingPacket:
                    SamplingConfig SamplingConfig = (SamplingConfig)packet.Data;
                    Mdl_Class.SamplingConfig = SamplingConfig;
                    Mdl_Class.SamplingConfiglist.Add(SamplingConfig);
                    if (result_SamplingConfig == null || result_SamplingConfig.IsCompleted)
                    {
                        result_SamplingConfig = new AddHandler_SamplingConfig(savedata.SaveSamplingConfig).BeginInvoke( null, null);

                    }
                    break;
                case PacketType.TimeSetting:
                    MachineTime machineTime = (MachineTime)packet.Data;
                    Mdl_Class.machineTime = machineTime;
                    if (result_MachineTime == null || result_MachineTime.IsCompleted)
                    {
                        result_MachineTime = new AddHandler_MachineTime(savedata.SaveMachineTime).BeginInvoke(machineTime, null, null);

                    }
                    break;
                //case PacketTypeSpeedConfig.:
                //    SpeedConfig bb = (SpeedConfig)packet.Data;
                //    RecieveListSC.Add(bb);
                //    break;
                //case PacketType.DATAPACKET:
                //    if (this.MyTcpIpMode == TcpIpMode.SlowMode)
                //    {
                //        DataPacket dpt = (DataPacket)packet.Data;
                //        //if (RecieveListSlowModeDataPacket.Count > 5000)
                //        //{
                //        //    RecieveListSlowModeDataPacket.RemoveRange(5000, RecieveListSlowModeDataPacket.Count - 5000);
                //        //    RecieveListSlowModeDataPacket.Add(dpt);
                //        //}
                //        //else
                //        //{
                //        //    RecieveListSlowModeDataPacket.Add(dpt);
                //        //}
                //        CurrentDataPacket = dpt;

                     
                //        //byte[] bytes9=new byte[]{dpt.InitialData[9].Data[1022].byte0,dpt.InitialData[9].Data[1022].byte1,dpt.InitialData[9].Data[1022].byte2,dpt.InitialData[9].Data[1022].byte3};
                //        //byte[] bytes10=new byte[]{dpt.InitialData[9].Data[1023].byte0,dpt.InitialData[9].Data[1023].byte1,dpt.InitialData[9].Data[1023].byte2,dpt.InitialData[9].Data[1023].byte3};
                //        //int a = BitConverter.ToInt32(bytes9,0);
                //        //int b = BitConverter.ToInt32(bytes10, 0);
                //        //Console.WriteLine("存入一个慢速模式的包");
                //        //Console.WriteLine("接收通道1"  + "一倍频幅值：" + dpt.OneMultiplierAmp[0].ToString());
                //        //Console.WriteLine("接收通道1" + "一倍频相位：" + dpt.OneMultiplierPhase[0].ToString());
                //    }
                //    if (this.MyTcpIpMode == TcpIpMode.FastMode)
                //    {
                //        DataPacket dpt = (DataPacket)packet.Data;
                //        RecieveListFastModeDataPacket.Add(dpt);
                //        CurrentDataPacket = dpt;
                //        //Console.WriteLine("存入一个快速模式的包");
                //    }
                //    break;
                default:
                    break;
            }


            }
            catch (Exception)
            {

                throw;
            }
        }



    
        public bool SendString(string text)
        {
            try
            {
                if (clientSocket == null || !clientSocket.Connected)
                {
                    clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    clientSocket.Connect(IPAddress.Parse(RemoteServerName.Trim()), RemoteServerPort);
                    NetworkStream netStream = new NetworkStream(clientSocket);
                    tcpPacketServiceClient = new Cls_NetPacketTcpAsynService(netStream);
                }

                (tcpPacketServiceClient as Cls_NetPacketTcpAsynService).OnAfterSendPacket -= _delegateSendPacket;
                //再次订阅事件
                (tcpPacketServiceClient as Cls_NetPacketTcpAsynService).OnAfterSendPacket += _delegateSendPacket;

                tcpPacketServiceClient.SendText(text);
                sendErrcount = 0;
                return true;
            }
            catch(Exception e)
            {
                Console.WriteLine("发送错误:"+e.Message);
                sendErrcount++;
                return true;

            }
        }

        public void SendACQParametersConfig(TCPIPControl.StructHelper.ACQParametersConfig acqc)
        {
            try
            {

    
            if (clientSocket == null || !clientSocket.Connected)
            {
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientSocket.Connect(IPAddress.Parse(RemoteServerName.Trim()), RemoteServerPort);
                NetworkStream netStream = new NetworkStream(clientSocket);
                tcpPacketServiceClient = new Cls_NetPacketTcpAsynService(netStream);
            }

                (tcpPacketServiceClient as Cls_NetPacketTcpAsynService).OnAfterSendPacket -= _delegateSendPacket;
            //再次订阅事件
            (tcpPacketServiceClient as Cls_NetPacketTcpAsynService).OnAfterSendPacket += _delegateSendPacket;
            tcpPacketServiceClient.SendACQParametersConfig(acqc);
            }
            catch (Exception ex)
            {

                throw;
            }
        }

        public void SendChannelConfig(TcpLabCommon.ChannelConfig chc)
        {
            try
            {

      
            if (clientSocket == null)
            {
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientSocket.Connect(IPAddress.Parse(RemoteServerName), RemoteServerPort);
                NetworkStream netStream = new NetworkStream(clientSocket);
                tcpPacketServiceClient = new Cls_NetPacketTcpAsynService(netStream);
            }

            (tcpPacketServiceClient as Cls_NetPacketTcpAsynService).OnAfterSendPacket -= _delegateSendPacket;
            //再次订阅事件
            (tcpPacketServiceClient as Cls_NetPacketTcpAsynService).OnAfterSendPacket += _delegateSendPacket;
            tcpPacketServiceClient.SendChannelConfig(chc);
            }
            catch (Exception)
            {


            }
        }

        public void SendTestPointConfig(TestPointConfig tpc)
        {
            try
            {

       
            if (clientSocket == null)
            {
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientSocket.Connect(IPAddress.Parse(RemoteServerName), RemoteServerPort);
                NetworkStream netStream = new NetworkStream(clientSocket);
                tcpPacketServiceClient = new Cls_NetPacketTcpAsynService(netStream);
            }

            (tcpPacketServiceClient as Cls_NetPacketTcpAsynService).OnAfterSendPacket -= _delegateSendPacket;
            //再次订阅事件
            (tcpPacketServiceClient as Cls_NetPacketTcpAsynService).OnAfterSendPacket += _delegateSendPacket;
            tcpPacketServiceClient.SendTestPointConfig(tpc);
            }
            catch (Exception)
            {

        
            }
        }



        public void SendSpeedConfig(TcpLabCommon.SpeedConfig sc)
        {
            try
            {

            if (clientSocket == null)
            {
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientSocket.Connect(IPAddress.Parse(RemoteServerName), RemoteServerPort);
                NetworkStream netStream = new NetworkStream(clientSocket);
                tcpPacketServiceClient = new Cls_NetPacketTcpAsynService(netStream);
            }

            (tcpPacketServiceClient as Cls_NetPacketTcpAsynService).OnAfterSendPacket -= _delegateSendPacket;
            //再次订阅事件
            (tcpPacketServiceClient as Cls_NetPacketTcpAsynService).OnAfterSendPacket += _delegateSendPacket;
            tcpPacketServiceClient.SendSpeedConfig(sc);

            }
            catch (Exception)
            {

            }
        }



        public void SendMachineTime(MachineTime sc)
        {
            try
            {

                if (clientSocket == null || !clientSocket.Connected)
                {
                    clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    clientSocket.Connect(IPAddress.Parse(RemoteServerName.Trim()), RemoteServerPort);
                    NetworkStream netStream = new NetworkStream(clientSocket);
                    tcpPacketServiceClient = new Cls_NetPacketTcpAsynService(netStream);
                }

                (tcpPacketServiceClient as Cls_NetPacketTcpAsynService).OnAfterSendPacket -= _delegateSendPacket;
                //再次订阅事件
                (tcpPacketServiceClient as Cls_NetPacketTcpAsynService).OnAfterSendPacket += _delegateSendPacket;
                tcpPacketServiceClient.SendMachineTime(sc);

            }
            catch (Exception)
            {

            }
        }


        public void SendSampling(SamplingConfig sc)
        {
            try
            {

                if (clientSocket == null || !clientSocket.Connected)
                {
                    clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    clientSocket.Connect(IPAddress.Parse(RemoteServerName.Trim()), RemoteServerPort);
                    NetworkStream netStream = new NetworkStream(clientSocket);
                    tcpPacketServiceClient = new Cls_NetPacketTcpAsynService(netStream);
                }

                (tcpPacketServiceClient as Cls_NetPacketTcpAsynService).OnAfterSendPacket -= _delegateSendPacket;
                //再次订阅事件
                (tcpPacketServiceClient as Cls_NetPacketTcpAsynService).OnAfterSendPacket += _delegateSendPacket;
                tcpPacketServiceClient.SendSamplingConfig(sc);

            }
            catch (Exception)
            {

            }
        }

        public void SendDataPacket(DataPacket dp)
        {
            try
            {

     
            if (clientSocket == null)
            {
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientSocket.Connect(IPAddress.Parse(RemoteServerName), RemoteServerPort);
                NetworkStream netStream = new NetworkStream(clientSocket);
                tcpPacketServiceClient = new Cls_NetPacketTcpAsynService(netStream);
            }
            //DataPacket dp = new DataPacket();
            //dp.InitialData = new Initialdata[32];
            //for (int i = 0; i < dp.InitialData.Length; i++)
            //{
            //    dp.InitialData[i] = new Initialdata();
            //    dp.InitialData[i].RPM = (UInt16)(20 + i);
            //}
            (tcpPacketServiceClient as Cls_NetPacketTcpAsynService).OnAfterSendPacket -= _delegateSendPacket;
            //再次订阅事件
            (tcpPacketServiceClient as Cls_NetPacketTcpAsynService).OnAfterSendPacket += _delegateSendPacket;
            tcpPacketServiceClient.SendDataPacket(dp);
            }
            catch (Exception)
            {


            }
        }

        public void TryConnect(int RetryCount)
        {
            string strres = MyPing.PingHost1(RemoteServerName);
            if (strres.Contains("Succes_Time"))
            {
                //int intres = int.Parse(strres.Split(':')[1]);
                //if (intres > 50)
                //{
                //    MyTcpIpState = TcpIpState.Fault;
                //}
                //else
                //{
                //    for (int i = 0; i < RetryCount; i++)
                //    {
                //       // SendString("HandShark,"+this.Master.HostIPAddress+","+this.Master.HostPort);
                //        SendString("HandShark");
                //        for (int j = 0; j < 4; j++)
                //        {
                //            Thread.Sleep(15);
                //            if (RecieveListString.Count >= 1)
                //            {
                //                string a = RecieveListString[0];

                //                if (a.Contains("HandSharkSucces"))
                //                {
                //                    MyTcpIpState = TcpIpState.Fault;
                //                    break;
                //                }
                //                RecieveListString.Clear();
                //            }
                //        }
                //if (MyTcpIpState == TcpIpState.Connection)
                    //        {

                    //            break;
                    //        }
                    //    }
                    //}
                    MyTcpIpState = TcpIpState.Connection;
            }
            else
            {
                MyTcpIpState = TcpIpState.Disconnection;
            }
        }

        public void TryConnect(int RetryCount, ACQParametersConfig aa)
        {
            string strres = MyPing.PingHost1(ServerName);
            if (strres.Contains("Succes_Time"))
            {
                int intres = int.Parse(strres.Split(':')[1]);
                if (intres > 50)
                {
                    MyTcpIpState = TcpIpState.Fault;
                }
                else
                {
                    for (int i = 0; i < RetryCount; i++)
                    {
                        // SendString("HandShark,"+this.Master.HostIPAddress+","+this.Master.HostPort);
                        SendString("HandShark");
                        for (int j = 0; j < 4; j++)
                        {
                            Thread.Sleep(15);
                            if (RecieveListString.Count >= 1)
                            {
                                string a = RecieveListString[0];

                                if (a.Contains("HandSharkSucces"))
                                {
                                    MyTcpIpState = TcpIpState.Fault;
                                    break;
                                }
                                RecieveListString.Clear();
                            }
                        }
                        if (MyTcpIpState == TcpIpState.Connection)
                        {
                           
                            break;
                        }
                    }
                }
            }
            else
            {
                MyTcpIpState = TcpIpState.Disconnection;
            }

            //SendACQParametersConfig(aa);
            TcpLabCommon.ChannelConfig ca = new TcpLabCommon.ChannelConfig();
            SendChannelConfig(ca);
        }

        public void SetSlowMode()
        {
            SendString("SlowMode");
            for (int j = 0; j < 4; j++)
            {
                Thread.Sleep(50);
                if (RecieveListString.Count >= 1)
                {
                    string a = RecieveListString[0]; ;
                    if (a.Contains("SlowMode"))
                    {
                        MyTcpIpMode = TcpIpMode.SlowMode;
                        break;
                    }
                    RecieveListString.RemoveAt(0);
                }
            }
        }

        public void SetFastMode()
        {
            SendString("FastMode");
            for (int j = 0; j < 4; j++)
            {
                Thread.Sleep(50);
                if (RecieveListString.Count >= 1)
                {
                    string a = RecieveListString[0]; ;
                    if (a.Contains("FastMode"))
                    {
                        MyTcpIpMode = TcpIpMode.FastMode;
                        break;
                    }
                    RecieveListString.RemoveAt(0);
                }
            }
        }



        public void GetPacket()
        {

        }
    }

    //public class CurrentDataPacketAndFFTData
    //{
    //    public DataPacket CurrentdataPacket { get; set; }
    //    public Dictionary<int, double[]> DicCHIDvsAmps { get; set; }
    //    public Dictionary<int, double[]> DicCHIDvsPhs { get; set; }
    //}

    public struct CurrentDataPacketAndFFTData
    {
        public DataPacket CurrentdataPacket;

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
        public ChVsAmpsAndPhs[] ChFFtAmpAndPhs;
    }

    public struct ChVsAmpsAndPhs
    {
        public Int16 CardID;

        public Int16 ChID;

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1024)]
        public float[] Amps;//振幅
        
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1024)]
        public float[] Phs;//相位

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1024)]
        public float[] DCs;//交流量

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1024)]
        public float[] ACs;//值流量

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1024)]
        public double[] ZDs;//原始数据震动值
    }
}
